package com.leon.android.arch

import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.billy.cc.core.component.CC
import kotlinx.android.synthetic.main.activity_main.*
import com.leon.android.arch.mvvv.api.Resource
import com.leon.android.arch.mvvv.api.Status
import com.leon.android.arch.mvvv.base.BaseActivity
import com.leon.android.common.extensions.*


class MainActivity : BaseActivity() {
    override val layoutId: Int
        get() = R.layout.activity_main

    val fragments:List<Fragment> by lazy {
        initFragments()
    }

    val pagerAdapter = object : FragmentStateAdapter(this) {
        override fun getItemCount(): Int {
            return fragments.size
        }

        override fun createFragment(position: Int): Fragment {
            return fragments[position]
        }

    }

    override fun initData(savedInstanceState: Bundle?) {

    }

    override fun initView(savedInstanceState: Bundle?) {
        vp2.adapter = pagerAdapter
        vp2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                when(position){
                    0 -> navigationView.selectedItemId = R.id.itemHome
                    1 -> navigationView.selectedItemId = R.id.itemExplore
                    2 -> navigationView.selectedItemId = R.id.itemMine
                }
            }
        })
        navigationView.setOnNavigationItemSelectedListener {
            when(it.itemId){
                R.id.itemHome -> {
                    vp2.currentItem = 0
                }
                R.id.itemExplore -> {
                    vp2.currentItem = 1
                }
                R.id.itemMine -> {
                    vp2.currentItem = 2
                }
            }
            true
        }
    }


    override fun bindModel() {

    }

    fun <T> updateViewByData(resource: Resource<T>, view: View, onSucceed: (T?) -> Unit) {
        when (resource.status) {
            Status.SUCCESS -> {
                onSucceed(resource.data)
                view.loadSuccess()
            }
            Status.ERROR -> {
                view.loadFailed()
            }
            Status.LOADING -> {
                view.loading()
            }
        }
    }

    fun initFragments():List<Fragment>{
        return listOf(
            CC.obtainBuilder("home").setActionName("fragment")
                .build().call().getDataItem("fragment"),
            CC.obtainBuilder("explore").setActionName("fragment")
                .build().call().getDataItem("fragment"),
            CC.obtainBuilder("mine").setActionName("fragment")
                .build().call().getDataItem("fragment")
        )
    }
}
